/*
 * @Author: hongbin
 * @Date: 2022-03-29 13:50:48
 * @LastEditors: hongbin
 * @LastEditTime: 2022-03-29 14:24:57
 * @Description:适配全屏方法
 */
import { useCallback, useEffect, useMemo } from "react";

type TUseFullScreenAdaptive = [
  fullscreenName: string,
  exitFullscreenName: string
];

/**
 * 适配各浏览器全屏方法名 必须交互才能施展全屏魔法
 * @param {function} callback 全屏状态更改回调
 */
const useFullScreenAdaptive = (
  callback?: () => void
): TUseFullScreenAdaptive => {
  const { type, fullscreenName, exitFullscreenName } = useMemo(() => {
    const { requestFullscreen, mozRequestFullScreen }: any =
      document.documentElement;

    if (requestFullscreen) {
      return {
        type: "fullscreenchange",
        fullscreenName: "requestFullscreen",
        exitFullscreenName: "exitFullscreen",
      };
    }
    if (mozRequestFullScreen) {
      return {
        type: "mozfullscreenchange",
        fullscreenName: "mozRequestFullScreen",
        exitFullscreenName: "mozCancelFullScreen",
      };
    }
    return {
      type: "webkitfullscreenchange",
      fullscreenName: "webkitRequestFullScreen",
      exitFullscreenName: "webkitCancelFullScreen",
    };
    // 没有IE
  }, []);

  const handleFullScreenChange = useCallback(() => {
    callback && callback();
  }, [callback]);

  useEffect(() => {
    document.addEventListener(type, handleFullScreenChange);

    return () => {
      document.removeEventListener(type, handleFullScreenChange);
    };
  }, [handleFullScreenChange, type]);

  return [fullscreenName, exitFullscreenName];
};

export default useFullScreenAdaptive;
